import os
import sys
import codecs
import json
import copy
import re
from typing import List, Dict, Tuple, Set, Union, Any, Optional
import csv
from tqdm import tqdm


def read_csv_file(filename: str) -> Dict[str, str]:
    # read file as csv format and then parse it into dict
    if not os.path.exists(filename):
        raise FileExistsError('filename not exists')

    dict_data: Dict[str, str] = dict()
    with codecs.open(filename, mode='r', encoding='utf-8') as f:
        render = csv.reader(f)  # reader(迭代器对象)--> 迭代器对象
        # get table header
        header_row = next(render)
        print('table header: {}, size of header: {}'.format(
            header_row, len(header_row)))  # 打印表头

        # get table data
        with tqdm(desc='Processing: ', colour='red') as pbar:
            for row in render:
                word_dict = dict()
                for i in range(len(header_row)):
                    word_dict[header_row[i]] = row[i]
                    # print('word_dict: {}'.format(word_dict))
                    dict_data[row[0]] = word_dict
        print('table data size: {}'.format(len(dict_data)))
    return dict_data


def read_json_file(json_filename: str) -> Dict[str, List[str]]:
    if not os.path.exists(json_filename):
        raise FileExistsError('json_filename not exists')
    with codecs.open(json_filename, 'r', 'utf-8') as f:
        json_file = json.load(f)
    return json_file


def parse_English_dict_entry(dict_line: str) -> Dict[str, str]:
    word2translation = dict()
    if len(dict_line) == 0:
        return word2translation

    # parse line as format: "n. 报告, 解释, 估价, 理由, 利润, 算账, 帐目\\nvi. 报帐, 解释, 导致, 报偿, 占, 杀死\\nvt. 认为\\n[计] 帐户, 帐号"
    # split by '\\n'
    dict_line.rstrip('\n,')
    translations = re.split(r'\\n', dict_line)
    for translation in translations:
        # split by ', '
        translation = translation.rstrip('\n,')
        translation_array = re.split(r",|\.| ", translation)
        key = translation_array[0]
        key = "adj" if key == "a" else key  # replace 'a' with 'adj'
        translation_vector = list()
        for word in translation_array[1:]:
            if len(word) > 0:
                translation_vector.append(word)
        if key in word2translation:
            for unit in translation_vector:
                word2translation[key].append(unit)
        else:
            word2translation[key] = translation_vector
    return word2translation


# main func()
if __name__ == '__main__':
    # sentence_example = 'n. 报告, 解释, 估价, 理由, 利润, 算账, 帐目\\nvi. 报帐, 解释, 导致, 报偿, 占, 杀死\\nvt. 认为\\n[计] 帐户, 帐号'
    # parse_English_dict_entry(sentence_example)
    raw_dict_filename = 'ECDICT//stardict.csv'
    final_json_filename = 'final.json'
    resource_dict = read_csv_file(raw_dict_filename)
    replace_table = read_json_file(final_json_filename)

    translation_dict: Dict[dict, dict] = dict()
    for key, value in replace_table.items():
        key2translations = dict()
        if key in resource_dict:
            translation = resource_dict[key]['translation']
            translation = parse_English_dict_entry(translation)
            # print('key: {}, value: {}'.format(key, translation))
            key2translations[key] = translation
        else:
            key2translations[key] = ""

        for unit in value:
            if unit in resource_dict:
                translation = resource_dict[unit]['translation']
                translation = parse_English_dict_entry(translation)
                # print('unit: {}, value: {}'.format(unit, translation))
                key2translations[unit] = translation
            else:
                key2translations[unit] = ""

        translation_dict[key] = key2translations
    # write translation_dict into json file
    with codecs.open('final_translation_dict.json', 'w', 'utf-8') as f:
        f.write(json.dumps(translation_dict, ensure_ascii=False, indent=4))
